package com.byit.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.byit.domain.AppNews;
import com.byit.domain.vo.DictVo;
import com.byit.mapper.AppNewsMapper;
import com.byit.service.IAppNewsService;
import com.byit.service.ISysDictService;
import com.byit.utils.IpUtils;
import com.byit.utils.MinioUtil;
import com.byit.utils.PageUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 新闻资讯
 */
@Service
public class AppNewsServiceImpl extends ServiceImpl<AppNewsMapper, AppNews> implements IAppNewsService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AppNewsMapper appNewsMapper;

    @Autowired
    private ISysDictService dictService;

    @Autowired
    private MinioUtil minioUtil;

    /**
     * nginx代理url
     */
    @Value("${minio.searchMinio}")
    private String searchMinio;

    @Override
    public void delAppnewsById(Map<String, Object> params) {
        appNewsMapper.delAppNewsById(params);
    }

    @Override
    public Page<JSONObject> selectAppnewsAll(Page<AppNews> pageInfo, Map<String, Object> params) {
        List<JSONObject> list = appNewsMapper.selectAppNewsAll(pageInfo, params);

//        list.forEach(appNewsInfo -> {
//            if (appNewsInfo.getInteger("sourceWay") == 1) {
//
//                /**
//                 * 简介获取内容前50各字符
//                 */String content1 = appNewsInfo.getString("content");
//                if (StringUtils.isNotEmpty(content1) && content1.length()>100) {
//                    String content = delHTML(content1);
//                    String intro = content.substring(0, 50);
//                    appNewsInfo.put("intro", intro);
//
//                }
//            }
//        });

//        list.forEach(appNews -> {
//            if (StringUtils.isNotEmpty(appNews.getString("picture"))) {
//
//                String picture = appNews.getString("picture");
//                appNews.put("picture", searchMinio + picture);
//            }
//
//        });
        Page<JSONObject> page = PageUtil.transform(pageInfo);

        page.setRecords(list);

        return page;
    }

    @Override
    public Page<JSONObject> selectPublishedAppnewsAll(Page<AppNews> pageInfo, Map<String, Object> params, HttpServletRequest request) {
        List<JSONObject> list = appNewsMapper.selectPublishedAppNewsAll(pageInfo, params);

        String ipAddr = IpUtils.getRequestURL(request);
        // String pictureUrls;
        list.forEach(appNewsInfo -> {

            //采集的新闻 添加简介
            if (StringUtils.isNotEmpty(appNewsInfo.getString("intro")) && appNewsInfo.getInteger("sourceWay") == 1) {

                /**
                 * 简介获取内容前50各字符
                 */
                String content1 = appNewsInfo.getString("content");
                if (StringUtils.isNotEmpty(content1) && content1.length()>200) {
                    String content = delHTML(content1);
                    if (content.length()>100) {

                        String intro = content.substring(0, 50);
                        appNewsInfo.put("intro", intro);
                    }

                }
            }
            //添加详情url
            appNewsInfo.put("detailsUrl", ipAddr + "/app/news/" + appNewsInfo.get("id") + ".html");
            //组装图片url
            String[] split = null;
            String pictureUrls = appNewsInfo.getString("picture");
            if (StringUtils.isNotEmpty(pictureUrls)) {
                split = pictureUrls.split(",");
                if (split.length > 3) {
                    String[] url3 = {split[0], split[1], split[2]};
                    appNewsInfo.put("picture", url3);
                } else {
                    appNewsInfo.put("picture", split);
                }
            }
            //添加置顶字段
            if (appNewsInfo.getInteger("level") == 0) {

                appNewsInfo.put("label", "置顶");
            }
        });

        Page<JSONObject> page = PageUtil.transform(pageInfo);

        page.setRecords(list);

        return page;
    }

    @Override
    public List<JSONObject> getAppNewsType(String type) {

        List<JSONObject> dictVos = dictService.selectAppNewsByType(type);
        //排序

        return dictVos;
    }

    @Override
    public String getPictrePath(MultipartFile file, String appNews) {

        String path;
        try {
            if (null == file) {
                return null;
            } else {
                JSONObject jsonObject = minioUtil.uploadFile(file.getInputStream(),
                        file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")), appNews + "/");
                if ("1".equals(jsonObject.getString("flag"))) {
                    return null;
                } else {
                    path = jsonObject.getString("path");
                    return path;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return null;
        }
    }

    @Override
    public String getSearchMinio() {
        return searchMinio;
    }

    public String delHTML(String htmlStr) {
        String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; //定义script的正则表达式
        String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; //定义style的正则表达式
        String regEx_html = "<[^>]+>"; //定义HTML标签的正则表达式

        Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
        Matcher m_script = p_script.matcher(htmlStr);
        htmlStr = m_script.replaceAll(""); //过滤script标签

        Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
        Matcher m_style = p_style.matcher(htmlStr);
        htmlStr = m_style.replaceAll(""); //过滤style标签

        Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
        Matcher m_html = p_html.matcher(htmlStr);
        htmlStr = m_html.replaceAll(""); //过滤html标签
        htmlStr = htmlStr.replaceAll("\n", "");
        return htmlStr.trim(); //返回文本字符串
    }
}
